# -*- coding:utf-8 -*-
import base64
import codecs
import re
from trace import pickle
import time
import sys

import datetime
from jsonpath import jsonpath
import json
import request_cicc.util
from my_dbUtil.dbInsert import soupDb
from request_cicc.cicc_standard_flow.log import Logger
from request_epicc_vpn.MyAdapter import MyAdapter
from request_epicc_vpn.calcUserYears import calc_user_years
from request_epicc_vpn.dbUtil import get_session
from request_epicc_vpn.getDataNew import caclAcl, caclPremium, compare_date, compare_time40
from request_epicc_vpn.standard_flow.dt_init import dt_init
from request_epicc_vpn.translateJsonToPremiun import readJson
import traceback

reload(sys)

sys.setdefaultencoding('utf-8')


global null, false, true
null = None
false = False
true = True
log=Logger()

def standard_main(renewal_data_dt,endDate=""):
    try:
        log.error("start")
        dt = dt_init()
        insuranceType = renewal_data_dt['insuranceType']
        insure_id = renewal_data_dt['insureCarId']
        group_id = insuranceType['insuranceTypeGroupId']
        if endDate=="":
            tomorrow = datetime.date.today() + datetime.timedelta(1)
            today = datetime.date.today()
            dt['ciStartDate'] = str(tomorrow)
            dt['ciEndDate'] = str(datetime.datetime.strptime((str(today.year + 1) + '-' + str(today.month) + '-' + str(today.day)),"%Y-%m-%d").date())
        else:
            endDate = datetime.datetime.strptime(endDate, "%Y-%m-%d").date()
            dt['ciStartDate'] = str(endDate)
            endDate = datetime.datetime.strptime((str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)),"%Y-%m-%d").date() + datetime.timedelta(-1)
            dt['ciEndDate'] = str(endDate)


        dt['vinNo'] = renewal_data_dt.get('vinNo', '')
        dt['licenseNo'] = renewal_data_dt.get('plateNumber', '')
        srssion = get_session()
        sessBase = srssion['2']
        req_session = pickle.loads(codecs.decode(sessBase.encode(), "base64"))
        req_session.mount('https://', MyAdapter())
        get_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMCheck.do?comCode=32012105&frameNo="+dt['vinNo']+"&licenseNo="
        get_checkcode_res = req_session.post(url=get_checkcode_url,verify=False).json()
        checkcode_res = jsonpath(get_checkcode_res, "$.data")
        dt['checkNo'] = checkcode_res[0][0]['checkNo']
        dt['checkCode'] = checkcode_res[0][0]['checkCode']
        dt['checkAnswer'] = request_cicc.util.pic2Str(base64.b64decode(dt['checkCode']))
        post_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMConfirm.do?comCode=32012105&checkNo="+dt['checkNo']+"&checkCode="+dt['checkAnswer']
        post_checkcode_res = req_session.post(url=post_checkcode_url,verify=False).json()
        post_checkcode_res = jsonpath(post_checkcode_res, "$.data")
        log.info(u'开始打码')
        count = 0
        while post_checkcode_res[0][0].get('errMessage', '') is not None:
            if '未匹配到交管车辆信息' in post_checkcode_res[0][0].get('errMessage',''):
                log.error("未匹配到交管车辆信息")
                #返回错误信息
                return post_checkcode_res[0][0].get('errMessage','')
            if '录入的校验码有误' in post_checkcode_res[0][0].get('errMessage',''):
                log.error("验证码有误，错误的验证码为,%s" % dt['checkAnswer'])
                get_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMCheck.do?comCode=32012105&frameNo=" + dt['vinNo'] + "&licenseNo="
                get_checkcode_res = req_session.post(url=get_checkcode_url, verify=False).json()
                checkcode_res = jsonpath(get_checkcode_res, "$.data")
                dt['checkNo'] = checkcode_res[0][0]['checkNo']
                dt['checkCode'] = checkcode_res[0][0]['checkCode']
                dt['checkAnswer'] = request_cicc.util.pic2Str(base64.b64decode(dt['checkCode']))
                post_checkcode_url = "http://10.134.136.112:8000/prpall/business/queryVehiclePMConfirm.do?comCode=32012105&checkNo=" + dt['checkNo'] + "&checkCode=" + dt['checkAnswer']
                post_checkcode_res = req_session.post(url=post_checkcode_url, verify=False).json()
                post_checkcode_res = jsonpath(post_checkcode_res, "$.data")
            if count>3:
                #验证码重发超限
                log.error("验证码重发超限")
                return "查询失败，稍后重试"
            count = count + 1

        if post_checkcode_res[0][0].get('errMessage', '') is None:
            log.info(u'打码成功')
            dt['modelCode'] = post_checkcode_res[0][0]['modelCode']
            car_info_url = "http://10.134.136.112:8000/prpall/vehicle/vehicleQuery.do?brandName=" + dt['modelCode'] + "&modelCode="
            car_info_res = req_session.post(url=car_info_url, verify=False).json()
            car_info_list = jsonpath(car_info_res, "$.data")
            if car_info_list:
                if len(car_info_list[0])>0:
                    log.info(u'获取车型成功，正在选取最低价车型')
                    car_info_list = car_info_list[0]
                    car_info_list.sort(key=lambda obj: obj.get('priceT'))
                    car_info = car_info_list[0]
                    if post_checkcode_res[0][0].get('enrollDate',None) is not None:
                        dt['enrollDate'] = str(time.strftime("%Y-%m-%d", time.localtime(int(post_checkcode_res[0][0]['enrollDate']['time']) / 1000)))
                    dt['licenseNo'] = post_checkcode_res[0][0]['id']['licenseNo']
                    dt['pmCarOwner'] = post_checkcode_res[0][0]['carOwner']
                    dt['exhaustScale'] = car_info['vehicleExhaust']
                    dt['engineNo'] = post_checkcode_res[0][0]['engineNo']
                    dt['brandName'] = car_info['vehicleName']
                    dt['purchasePriceOld'] = str(car_info['priceTr'])
                    dt['frameNo'] = dt['vinNo']
                    dt['modelCode'] = car_info['vehicleId']
                    dt['seatCount'] = car_info['vehicleSeat']
                    useYears = calc_user_years(dt['ciStartDate'], dt['enrollDate'])
                    dt['prpCitemCar_useYears'] = useYears
                    acl_price = caclAcl(dt, req_session)
                    dt['aclPrice'] = acl_price
                    insuranceType = {
                      "insuranceTypeGroupId": "6",
                      "insuranceTypeGroup": "88888888",
                      'compulsoryInsurance': "1",
                      'nAggTax': '1',
                      'otherHurtPremium': {
                        "isCheck": "1",
                        "Amount": "500000"
                      },
                      'carNickPremium': {
                        "isCheck": "1",
                        "Amount": "2000"
                      },
                      'driverDutyPremium': {
                        "isCheck": "1",
                        "Amount": "10000"
                      },
                      'passengerDutyPremium': {
                        "isCheck": "1",
                        "Amount": "10000"
                      },
                      'glassBrokenPremium': "1",
                      'carFirePremium': "1",
                      'engineWadingPremium': "1",
                      'carTheftPremium': "1",
                      'carDamagePremium': "1",
                      'carDamageBenchMarkPremium': '1',
                      'otherHurtBenchMarkPremium': '1',
                      'carTheftBenchMarkPremium': '1',
                      'driverDutyBenchMarkPremium': '1',
                      'passengerBenchMarkPremium': '1',
                      'carNickBenchMarkPremium': '1',
                      'carFireBrokenBenchMarkPremium': '1',
                      'engineWadingBenchMarkPremium': '1'
                    }
                    price_res = caclPremium(dt, insuranceType, req_session)
                    while price_res['data'][0].get('errMessage') is not None:
                        if '重复投保' in price_res['data'][0].get('errMessage'):
                            str1 = "\d{4}-\d{2}-\d{2}"
                            datelist = re.findall(str1, price_res['data'][0]['errMessage'], re.S)
                            if len(datelist) == 2:
                                endDate = compare_date(datelist[0], datelist[1])
                                dayGap = compare_time40(str(endDate))
                                if dayGap >= 40:
                                    log.error("重复投保，上期保单超过40天")
                                    return price_res['data'][0]['errMessage'].encode('utf-8')
                                else:
                                    dt['ciStartDate'] = str(endDate)
                                    endDate = datetime.datetime.strptime((str(endDate.year + 1) + '-' + str(endDate.month) + '-' + str(endDate.day)),"%Y-%m-%d").date() + datetime.timedelta(-1)
                                    dt['ciEndDate'] = str(endDate)
                                    useYears = calc_user_years(dt['ciStartDate'], dt['enrollDate'])
                                    dt['prpCitemCar_useYears'] = useYears
                                    acl_price = caclAcl(dt, req_session)
                                    dt['aclPrice'] = acl_price
                                    price_res = caclPremium(dt, insuranceType, req_session)
                    log.error("开始解析保费信息")
                    PremiumInfo = readJson(price_res['data'][0]['biInsuredemandVoList'][0]['prpCitemKinds'],price_res['data'][0].get('ciInsureVOList',None ))
                    log.info(PremiumInfo)
                    # data=[开始时间,结束时间，座位数，组合id，车辆id，公司id]
                    data_list = [dt['ciStartDate'], dt['ciEndDate'], dt['seatCount'],group_id, insure_id, '2']

                    soupDb(PremiumInfo, data_list)
                    log.info(u'人保入库成功')
                    return None
                else:
                    log.error(u'无法获取车型')
                    return ('无法获取车型')
    except Exception,e:
        log.error(traceback.format_exc())
        return "未知错误"

if __name__=="__main__":
    standard_main()